package org.shiro.demo.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.shiro.demo.entity.Category;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.service.ICategoryService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/category")
public class CategoryController {
	@Resource(name = "categoryService")
	private ICategoryService categoryService;

	@RequestMapping(value = "/modify")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("category-administrator")
	public Object modifyByid(Category object) {
		ResponseResult rr = new ResponseResult();
		try {
			categoryService.update(object);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;
	}

	/**
	 * 
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("category-administrator")
	public Object add(@RequestParam(value = "description", required = true) String description, @RequestParam(value = "imageid", required = true) String imageId) {
		ResponseResult rr = new ResponseResult();
		Category category = new Category();
		category.setDescription(description);
		category.setImageId(imageId);
		try {
			categoryService.save(category);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;
	}

	@RequestMapping(value = "/list")
	public @ResponseBody List<Category> list() {
		List<Category> categories = categoryService.getAll(Category.class);
		return categories;
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("category-administrator")
	public Object deleteCategory(@RequestParam(value = "id", required = true) long id) {
		ResponseResult rr = new ResponseResult();
		try {
			categoryService.delete(Category.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;
	}

}
